<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Utility methods used by the metadata extraction library.
 */
class metaextractor_Util
{
	/**
	 * Extract the primaryTopic URI of a (X)HTML resource.
	 * see: http://esw.w3.org/SweoIG/TaskForces/CommunityProjects/LinkingOpenData/AutoDiscovery
	 * @param string $html HTML content
	 * @param string $url URL of the (X)HTML resource
	 * @return string primaryTopic URI or null if no primaryTopic URI was found 
	 */	
	public static function extractPrimaryTopicUriFromHtml($html, $url)
	{
		// extract LINK tags with rel="[...]primaryTopic"
		preg_match_all('~<link [^>]*rel="[^"]*primaryTopic"[^>]*>~ims', $html, $matches);
		//print_r($matches);
		$linkTags = $matches[0];
		
		// parse LINK tags
		foreach($linkTags as $linkTag)
		{
			preg_match_all('~([-a-z]+) *= *((?:"[^"]*")|(?:\'[^\']*\'))~ims', $linkTag, $matches);
			foreach($matches[1] as $attributeIdx => $attributeName)
			{
				if(strtolower($attributeName) == 'href')
				{
					return self::convertRelativeToAbsoluteUrl($url, trim(html_entity_decode(substr($matches[2][$attributeIdx], 1, -1))));
				}
			}
		}
		
		return null;
	}
	
	/**
	 * Extract the primaryTopic URI from HTTP headers.
	 * see: http://esw.w3.org/SweoIG/TaskForces/CommunityProjects/LinkingOpenData/AutoDiscovery
	 * @param array $httpHeaders HTTP headers
	 * @param string $url URL of the HTTP resource
	 * @return string primaryTopic URI or null if no primaryTopic URI was found 
	 */	
	public static function extractPrimaryTopicUriFromHttpHeaders($httpHeaders, $url)
	{
		foreach($httpHeaders as $httpHeader)
		{
			if(preg_match('~^Link:~i', $httpHeader) && preg_match('~rel="[^"]*primaryTopic"~i', $httpHeader) && preg_match('~<([^>]+)>~', $httpHeader, $urlMatches))
			{
				// primaryTopic URL
				// see: http://esw.w3.org/SweoIG/TaskForces/CommunityProjects/LinkingOpenData/AutoDiscovery 
				return self::convertRelativeToAbsoluteUrl($url, $urlMatches[1]);
			}
		}
		
		return null;
	}
	
	/**
	 * Get the base URL part from a URL.
	 * @param string $url URL
	 * @return string base URL
	 */
	public static function getBaseUrl($url)
	{
		if(!preg_match('~/$~', $url))
		{
			// the URL does not end with a '/' character
			
			// first remove any hash parameters
			$url = preg_replace('~#.*~', '', $url);
			
			// then remove everything after the last '/'
			$url = preg_replace('~/[^/]+$~', '/', $url);
		}
		
		return $url;
	}
	
	/**
	 * Convert a relative URL to an absolute URL.
	 * @param string $baseUrl base URL
	 * @param string $relativeUrl relative URL
	 * @return string absolute URL
	 */
	public static function convertRelativeToAbsoluteUrl($baseUrl, $relativeUrl)
	{
		if(preg_match('/^[a-z0-9]{2,}\:[^\s]+$/is', $relativeUrl))
		{
			// $relativeUrl is already absolute
			return $relativeUrl;
		}
		else
		{
			// make sure that the base URL is a proper base URL
			$baseUrl = self::getBaseUrl($baseUrl);
			
			if(!preg_match('~^/~', $relativeUrl))
			{
				// the relative URL doesn't start with a '/' character, simply concatenate it to the base URL
				return $baseUrl . $relativeUrl;
			}
			else
			{
				// the relative URL starts with a '/' character
				
				// calculate the server root URL
				$rootUrl = preg_replace('~^([^:]+://[^/]+).*$~', '$1', $baseUrl);
				
				// concatenate the root URL and the relative URL
				return $rootUrl . $relativeUrl;
			}
		}
	}
}